# -*- coding:utf-8 -*-
__author__ = "daoyu"
__date__ = "2023-6-29"
__doc__ = "封装pymysql"

import pymysql
import traceback
import os,sys
sys.path.append(os.getcwd())
from utils.yaml_client import YamlClient

class MysqlClient:

    def __init__(self, dbconfig=YamlClient().load_yaml(r"conf\mysql_config.yaml")):
        """
            初始化
        """
        self.dbconfig = dbconfig
        self.__connect = self.__get_connect()
        self.__cursor = self.__get_cursor()

    def __get_connect(self):
        """
            获取数据库连接对象
        """
        return pymysql.connect(**self.dbconfig)

    def __get_cursor(self):
        """
            获取游标对象
        """
        return self.__connect.cursor()

    def query(self, sql):
        """
            查询
        """
        result = ()
        try:
            self.__cursor.execute(sql)
            result = self.__cursor.fetchall()
        except:
            traceback.print_exc()
        finally:
            return result

    def update(self, sql):
        """
            新增/修改/删除
        """
        result = False
        try:
            flag = self.__cursor.execute(sql)
            self.__connect.commit()
            result = True if flag else False
        except:
            self.__connect.rollback()
            traceback.print_exc()
        finally:
            return result

    def __del__(self):
        """
            析构
        """
        self.__cursor.close()
        self.__connect.close()

if __name__ == "__main__":
    update = MysqlClient().update("update tb_user set nickName = '123456' where userPhone = 13688886700")
    query = MysqlClient().query("select * from tb_user where userPhone = 13688886700 and nickName = '123456'")
    print(update)
    print(query)